/**
 * 
 */
package com.itee.protocal.meter;

import com.itee.core.util.StringCoder;
import org.apache.commons.lang.ArrayUtils;


/**
 * @author gonglei
 * 
 */
public class MeterPacket {

	private byte[] meterAddress;

	private String address;

	private byte cmd;

	private byte[] datas;

	public MeterPacket(byte[] meterAddress, byte cmd, byte[] datas) {
		this.meterAddress = meterAddress;
		this.cmd = cmd;
		this.datas = datas;
	}

	public MeterPacket(String address, byte cmd, byte[] datas) {
		this.address = address;
		this.cmd = cmd;
		this.datas = datas;
	}

	public byte[] getMeterAddress() {
		return meterAddress;
	}

	public void setMeterAddress(byte[] meterAddress) {
		this.meterAddress = meterAddress;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public byte getCmd() {
		return cmd;
	}

	public void setCmd(byte cmd) {
		this.cmd = cmd;
	}

	public byte[] getDatas() {
		return datas;
	}

	public void setDatas(byte[] datas) {
		this.datas = datas;
	}
	
	public byte getDataLength(){
		return (byte)datas.length;
	}
	
	public byte[] getDataFlag(){
		if(datas != null && datas.length >= 4){
			byte[] dataFlag = new byte[4];
			System.arraycopy(datas, 0, dataFlag, 0, 4);
			return dataFlag;
		} else {
			return new byte[0];
		}
	}

	public byte[] toBytes() {
		byte[] dataBytes = new byte[12 + datas.length];
		dataBytes[0] = DL645.POS_BEGIN;
		if (meterAddress != null) {
			System.arraycopy(meterAddress, 0, dataBytes, 1, 6);
		} else if (address != null) {
			meterAddress = StringCoder.hexStringToByte(address);
			ArrayUtils.reverse(meterAddress);
			System.arraycopy(meterAddress, 0, dataBytes, 1, 6);
		}

		dataBytes[7] = DL645.POS_BEGIN;
		dataBytes[8] = cmd;
		// 长度
		dataBytes[9] = (byte) datas.length;
		
		System.arraycopy(datas, 0, dataBytes, 10, datas.length);
		for (int i = 0; i < (datas.length); i++) {
			dataBytes[i+10] += 0x33;
		}

		byte sum = 0;
		for (int i = 0; i < (dataBytes.length - 2); i++) {
			sum += dataBytes[i];
		}
		dataBytes[dataBytes.length - 2] = sum;
		dataBytes[dataBytes.length - 1] = DL645.POS_END;
		return dataBytes;
	}

}
